package cc.angis.xiugallery.image.ui;

import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import cc.angis.xiugallery.BuildConfig;
import cc.angis.xiugallery.R;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.db.FavouriteDBHelper;
import cc.angis.xiugallery.db.FavouriteImagesDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.image.util.ImageCache;
import cc.angis.xiugallery.image.util.ImageCache.ImageCacheParams;
import cc.angis.xiugallery.image.util.ImageResizer;
import cc.angis.xiugallery.image.util.ThumbnailImageLoader;
import cc.angis.xiugallery.image.util.Utils;
import cc.angis.xiugallery.provider.GalleryImageProvider;
import cc.angis.xiugallery.provider.ISourceProvider;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class SelectImageGridFragment extends SherlockFragment implements AdapterView.OnItemClickListener {
	private static final String TAG = "SelectImageGridFragment";
	 private static final String IMAGE_CACHE_DIR = "thumbs";

	 protected int mImageThumbSize;
	    protected int mImageThumbSpacing;
	    protected ImageAdapter mAdapter;
	    protected ImageResizer mImageWorker;
	    protected ISourceProvider mProvider;
	    private String favId;
	    private String bucketId;
	
	private List<Long> selectedImgs;
	
	private boolean isChanged = false;
	
	/**
     * Factory method to generate a new instance of the fragment given an image number.
     *
     * @param imageNum The image number within the parent adapter to load
     * @return A new instance of ImageDetailFragment with imageNum extras
     */
    public static SelectImageGridFragment newInstance(String favId, String bucketId) {
        final SelectImageGridFragment f = new SelectImageGridFragment();
        final Bundle args = new Bundle();
        args.putString(GlobalConst.INTENT_FAVOURITE_ID, favId);
        args.putString(GlobalConst.INTENT_BUCKET_ID, bucketId);
        f.setArguments(args);
        return f;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
         setHasOptionsMenu(true);
         ActionBar actionbar = getSherlockActivity().getSupportActionBar();
		 actionbar.setTitle(R.string.title_selectfrom);
         favId = getArguments().getString(GlobalConst.INTENT_FAVOURITE_ID);
         bucketId = getArguments().getString(GlobalConst.INTENT_BUCKET_ID);
         mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
         mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
         mProvider = new GalleryImageProvider(getActivity(), bucketId);
         mAdapter = new ImageAdapter(getActivity());
         ImageCacheParams cacheParams = new ImageCacheParams(IMAGE_CACHE_DIR);

         // Allocate a third of the per-app memory limit to the bitmap memory cache. This value
         // should be chosen carefully based on a number of factors. Refer to the corresponding
         // Android Training class for more discussion:
         // http://developer.android.com/training/displaying-bitmaps/
         // In this case, we aren't using memory for much else other than this activity and the
         // ImageDetailActivity so a third lets us keep all our sample image thumbnails in memory
         // at once.
         cacheParams.memCacheSize = 1024 * 1024 * Utils.getMemoryClass(getActivity()) / 3;

         // The ImageWorker takes care of loading images into our ImageView children asynchronously
         mImageWorker = new ThumbnailImageLoader(getActivity(), mImageThumbSize,Thumbnails.MICRO_KIND);
         mImageWorker.setAdapter(mProvider);
         mImageWorker.setLoadingImage(R.drawable.empty_photo);
         mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(), cacheParams));
    	FavouriteImagesDBHelper dbHelper = new FavouriteImagesDBHelper(getActivity(), TableConstants.TABLE_FAVOURITE_IMAGES);
    	selectedImgs = dbHelper.getAllByFavId(Integer.parseInt(favId));
    	dbHelper.closeDB();
    	mAdapter = new ImageAdapter(getActivity());
    }
    
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);
        final GridView mGridView = (GridView) v.findViewById(R.id.gridView);
        mProvider.initSource();
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(this);

        // This listener is used to get the final width of the GridView and then calculate the
        // number of columns and the width of each column. The width of each column is variable
        // as the GridView has stretchMode=columnWidth. The column width is used to set the height
        // of each view so we get nice square thumbnails.
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (mAdapter.getNumColumns() == 0) {
                            final int numColumns = (int) Math.floor(
                                    mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
                            if (numColumns > 0) {
                                final int columnWidth =
                                        (mGridView.getWidth() / numColumns) - mImageThumbSpacing;
                                mAdapter.setNumColumns(numColumns);
                                mAdapter.setItemHeight(columnWidth);
                                if (BuildConfig.DEBUG) {
                                    Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                                }
                            }
                        }
                    }
                });

        return v;
    }
    
    @Override
    public void onResume() {
        super.onResume();
        mImageWorker.setExitTasksEarly(false);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
        mImageWorker.setExitTasksEarly(true);
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    	isChanged = true;
    	if (!isSelected(position)){
    		v.findViewById(R.id.selectedlayout).setVisibility(View.VISIBLE);
    		selectedImgs.add(0, (Long)mProvider.getItem(position));
    	}
    	else {
    		v.findViewById(R.id.selectedlayout).setVisibility(View.GONE);
    		selectedImgs.remove((Long)mProvider.getItem(position));
    	}
    }
    
    private boolean isSelected(int position){
    	for (Long selectedImg : selectedImgs){
    		if (((Long)mProvider.getItem(position)).longValue() == selectedImg.longValue()){
        		return true;
        	}
    	}
    	return false;
    }
    
    /**
     * The main adapter that backs the GridView. This is fairly standard except the number of
     * columns in the GridView is used to create a fake top row of empty views as we use a
     * transparent ActionBar and don't want the real top row of images to start off covered by it.
     */
    private class ImageAdapter extends BaseAdapter {

        private final Context mContext;
        private int mItemHeight = 0;
        private int mNumColumns = 0;
        private int mActionBarHeight = -1;
        private GridView.LayoutParams mFolderViewLayoutParams;

        public ImageAdapter(Context context) {
            super();
            mContext = context;
            mFolderViewLayoutParams = new GridView.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }

        @Override
        public int getCount() {
            // Size of adapter + number of columns for top empty row
            return mImageWorker.getAdapter().getSize();
        }

        @Override
        public Object getItem(int position) {
        	return mImageWorker.getAdapter().getImageItem(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            // Two types of views, the normal ImageView and the top row of empty views
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
        	 return 0;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup container) {
            // Now handle the main ImageView thumbnails
        	View view;
            ImageView imageView;
            RelativeLayout selectedLayout;
//            ImageView selectedView;
            if (convertView == null) { // if it's not recycled, instantiate and initialize
            	view = SelectImageGridFragment.this.getLayoutInflater(getArguments()).inflate(R.layout.imagegrid, null);
            	view.setLayoutParams(mFolderViewLayoutParams);
            	
            	imageView = (ImageView)view.findViewById(R.id.images);
            	selectedLayout = (RelativeLayout) view.findViewById(R.id.selectedlayout);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//                selectedView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                selectedView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            } else { // Otherwise re-use the converted view
            	view = convertView;
            	imageView = (ImageView)convertView.findViewById(R.id.images);
            	selectedLayout = (RelativeLayout) convertView.findViewById(R.id.selectedlayout);
            }

            // Check the height matches our calculated column width
            if (view.getLayoutParams().height != mItemHeight) {
            	view.setLayoutParams(mFolderViewLayoutParams);
            }

            // Finally load the image asynchronously into the ImageView, this also takes care of
            // setting a placeholder image while the background thread runs
            mImageWorker.loadImage(position, imageView);
            if (isSelected(position))
            	selectedLayout.setVisibility(View.VISIBLE);
            else
            	selectedLayout.setVisibility(View.GONE);
            return view;
        }

        /**
         * Sets the item height. Useful for when we know the column width so the height can be set
         * to match.
         *
         * @param height
         */
        public void setItemHeight(int height) {
            if (height == mItemHeight) {
                return;
            }
            mItemHeight = height;
            mFolderViewLayoutParams =
                    new GridView.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
            mImageWorker.setImageSize(height);
            notifyDataSetChanged();
        }

        public void setNumColumns(int numColumns) {
            mNumColumns = numColumns;
        }

        public int getNumColumns() {
            return mNumColumns;
        }
    }

    @Override
	public void onDestroyView() {
		final ImageCache cache = mImageWorker.getImageCache();
        if (cache != null) {
            mImageWorker.getImageCache().clearCaches();
//            DiskLruCache.clearCache(getActivity(), ImageFetcher.HTTP_CACHE_DIR);
//            Toast.makeText(getActivity(), R.string.clear_cache_complete,
//                    Toast.LENGTH_SHORT).show();
        }
		super.onDestroyView();
	}
    
    private class SaveFavImageTast extends AsyncTask<String, Void, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			int result = -1;
			FavouriteImagesDBHelper dbHelper  = new FavouriteImagesDBHelper(getActivity(), TableConstants.TABLE_FAVOURITE_IMAGES);
			FavouriteDBHelper helper  = new FavouriteDBHelper(getActivity(), TableConstants.TABLE_FAVOURITE);
			try {
				dbHelper.delete(Integer.parseInt(favId));
				for (Long imgId : selectedImgs){
					dbHelper.insert(Integer.parseInt(favId), imgId, "");
				}
				if (selectedImgs.size() >0)
					helper.update(Integer.parseInt(favId), null, selectedImgs.get(0),selectedImgs.size());
				result = 0;
			} catch (Exception e){
				e.printStackTrace();
			} finally{
				dbHelper.closeDB();
				helper.closeDB();
			}
			return result;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (result == 0){
				getActivity().finish();
			}
		}
    	
    }
    
    @Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu3, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch(item.getItemId()){
			case android.R.id.home:
				if (getActivity() instanceof SlidingFragmentActivity){
					((SlidingFragmentActivity)getActivity()).getSlidingMenu().showBehind();
				} else
					getActivity().finish();
				break;
			case R.id.finish_img_fav_button:
				if(isChanged)
					new SaveFavImageTast().execute();
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
}
